package org.myspringframework.context.annotation;

import org.myspringframework.beans.factory.config.beandefinition.BeanDefinition;
import org.myspringframework.beans.factory.config.beandefinition.BeanDefinitionRegistry;

import java.util.Set;

//扫描包处理的类
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {

    private BeanDefinitionRegistry registry;

    public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
        this.registry = registry;
    }

    //扫描basePackages下的@Component类并注册beanDefinition
    public void doScan(String... basePackages) {
        for (String basePackage : basePackages) {
            //扫描包下带@Component注解的类
            Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
            for (BeanDefinition beanDefinition : candidates) {
                // 解析 Bean 的作用域 singleton、prototype
                String beanScope = resolveBeanScope(beanDefinition);
                if (beanScope!=null&&beanScope!="") {
                    beanDefinition.setScope(beanScope);
                }

                //注册beanDefiniyion
                registry.registerBeanDefinition(determineBeanName(beanDefinition), beanDefinition);
            }
        }
    }

    private String resolveBeanScope(BeanDefinition beanDefinition) {
        Class<?> beanClass = beanDefinition.getBeanClass();
        Scope scope = beanClass.getAnnotation(Scope.class);
        if (null != scope) return scope.value();
        return "";
    }

    //解析Component的类的beanName
    private String determineBeanName(BeanDefinition beanDefinition) {
        Class<?> beanClass = beanDefinition.getBeanClass();
        Component component = beanClass.getAnnotation(Component.class);
        Controller controler = beanClass.getAnnotation(Controller.class);
        Service service = beanClass.getAnnotation(Service.class);
        String beanName=null;
        if (component!=null){
            beanName = component.value();
        }else if (controler!=null){
            beanName=controler.value();
        }else if (service!=null){
            beanName=service.value();
        }
        if (beanName!=null&&beanName!="") {
            //没有指定Bean名称,BeanName默认为类名首字母小写
            String className = beanDefinition.getBeanClass().getSimpleName();
            beanName = String.valueOf(className.charAt(0)).toLowerCase() + className.substring(1);
        }
        return beanName;
    }

}